<template>
  <div class="app-container">
    <el-carousel
      height="87px"
      arrow="never"
      indicator-position="outside"
      trigger="click"
      :autoplay="false"
      style="margin-bottom: 5px"
      class="desk"
    >
      <el-carousel-item v-for="index1 in 1" :key="index1">
        <ul class="top-ui">
          <li v-for="(content, index) in topStatics" class="clearfix" :key="index">
            <el-card style="width: 100%" shadow="always">
              <div class="taskAll">
                <el-row>
                  <el-col :span="12" class="taski">
                    <el-row>
                      <el-col :span="24"
                        ><span class="title-dot" :style="'background-color:' + content.backgroundColor"></span>{{ content.title }}</el-col
                      >
                      <el-col :span="24">
                        {{ content.title1 }} <b>{{ content.total1 }}</b>
                      </el-col>
                      <el-col :span="24">
                        {{ content.title2 }} <b>{{ content.total2 }}</b>
                      </el-col>
                    </el-row>
                  </el-col>
                  <el-col :span="12" style="height: 100%">
                    <div style="width: 100%; height: 72px" :id="'chart' + index"></div>
                  </el-col>
                </el-row>
              </div>
            </el-card>
          </li>
        </ul>
      </el-carousel-item>
    </el-carousel>
    <el-row :gutter="5" style="margin-bottom: 5px">
      <el-col :span="12">
        <el-card class="card_width" style="height: 419.5px">
          <el-row>
            <p class="pinformation">待办事项</p>
            <p class="totalStyle">共 {{ total }} 条数据</p>
            <el-button
              link
              @click="handleAllTodo()"
              style="margin-bottom: 5px; margin-left: 15px"
              >所有待办</el-button
            >
          </el-row>
          <el-row :gutter="5">
            <el-col :span="24">
              <el-row :gutter="5">
                <el-col :span="4" v-for="item in taskCountList">
                  <span
                    style="display: inline-block; white-space: nowrap; width: 100%"
                    @click="handleAllTodo(item.category, item.taskDefKey)"
                  >
                    <span class="number_sub">{{ item.taskCount }}</span>
                    <span class="text_sub">{{ item.taskName }}</span>
                  </span>
                  <!-- <el-button color="#626aef" :dark="isDark" v-for="item in taskCountList"  plain>{{ item.taskCount }}{{ item.taskName }}</el-button> -->
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-table
            ref="mainTableRef"
            v-loading="loading"
            :data="needDealList"
            style="margin-top: 5px"
            :height="total ? '300px' : '360px'"
          >
            <el-table-column
              label="流程类型"
              align="center"
              prop="categoryName"
              width="140"
              show-overflow-tooltip
            />
            <el-table-column
              label="事项名称"
              align="center"
              prop="title"
              show-overflow-tooltip
            />
            <el-table-column
              label="任务节点"
              align="center"
              prop="taskName"
              width="110"
              show-overflow-tooltip
            />
            <el-table-column
              label="上一状态时间"
              align="center"
              prop="createTime"
              width="140"
              show-overflow-tooltip
            >
            <template #default="scope">
              {{scope.row.createTime.substring(0,16)}}
              </template>
              </el-table-column>
            <el-table-column label="操作" align="center" width="65">
              <template #default="scope">
                <el-button link @click="handleProcess(scope.row)">办理</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
            :pageSizes="[5, 10, 20, 40]"
          />
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-row :gutter="5" style="margin-bottom: 5px">
          <el-col :span="24">
            <el-card class="card_width" style="height: 100px">
              <p class="pinformation">常用菜单</p>
              <el-row style="justify-content: space-between; margin-top: 10px">
                <el-col
                  :span="2"
                  v-for="item in commonUseList"
                  style="text-align: center"
                >
                  <div
                    style="
                      height: 30px;
                      width: 30px;
                      margin: 0 auto;
                      border-radius: 10px;
                      margin-bottom: 8px;
                      font-size: 20px;
                      color: #fff;
                      background-color: skyblue;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                      cursor: pointer;
                    "
                  >
                    <svg-icon :icon-class="item.icon" />
                  </div>
                  <div style="font-size: 12px">{{ item.label }}</div>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="12">
            <el-card style="height: 314px">
              <p class="pinformation" style="position: absolute">通知公告</p>
              <el-tabs v-model="activityName" class="demo-tabs">
                <el-tab-pane label="未读" name="first">
                  <isRead v-if="activityName == 'first'" ref="isReadRef" />
                </el-tab-pane>
                <el-tab-pane label="已读" name="second">
                  <isRead v-if="activityName == 'second'" ref="isReadRef" />
                </el-tab-pane>
              </el-tabs>
            </el-card>
          </el-col>
          <el-col :span="12" :gutter="5">
            <el-card style="height: 314px"> </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-row :gutter="5" style="margin-bottom: 5px" id="deptTj">
      <el-col :span="24">
        <el-card class="card_width" :style="'height:' + autoHeight + 'px'">
          <el-row>
            <p class="pinformation">部门任务</p>
          </el-row>
          <el-row>
            <el-col :span="18">
              <!-- <p class="pinformation">月度工作量统计（采样/分析）</p> -->
              <div id="leftChar" :style="'height:' + autoHeight + 'px'"></div>
            </el-col>
            <el-col :span="6">
              <!-- <p class="pinformation">月度工作量统计（登记/评审）</p> -->
              <div id="rightChar" :style="'height:' + autoHeight + 'px'"></div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    <sampleView ref="sampleViewRef"></sampleView>
    <checkDialog ref="checkRef"></checkDialog>
    <newBuiltTab ref="writeRef"></newBuiltTab>
  </div>
</template>

<script setup name="Index">
import checkDialog from "@/views/lab/labTask/checkDialog";
import newBuiltTab from "@/views/lab/labMethod/newBuilt";
import sampleView from "@/views/sampleManage/sampleQc/components/sampleView";
import { queryProgressList } from "@/api/taskProgressDetails/index";
import bus from "@/utils/eventBus";
import { todoList, todoCount } from "@/api/flowable/todo";
import isRead from "./isRead.vue";
import useRouteView from "@/store/modules/routeView";
import { getCurrentTime } from "@/api/common";

import * as echarts from "echarts";
import "echarts-liquidfill";
const { proxy } = getCurrentInstance();

const router = useRouter();
const route = useRoute();
const activityName = ref("first");
const isReadRef = ref(null);
const checkRef = ref(null);
const writeRef = ref(null);
const sampleViewRef = ref(null);
const completeForm = ref({
  projectCount: 35,
  sampleCount: 12,
  labCount: 12,
  radeCount: 12,
  qfCount: 3,
});

const routeViewStore = useRouteView();

const taskCountList = ref([]);

const needDealList = ref([]);
const queryParams = ref({
  pageNum: 1,
  pageSize: 5,
});
const queryProgressParams = ref({
  pageNum: 1,
  pageSize: 5,
});
const total = ref(0);
const progressTotal = ref(0);
const commonUseList = ref([
  { path: "/index", label: "合同登记", icon: "post" },
  { path: "/index", label: "合同评审", icon: "druid" },
  { path: "/index", label: "方案评审", icon: "log" },
  { path: "/index", label: "任务计划", icon: "education" },
  { path: "/index", label: "样品领取", icon: "edit" },
  { path: "/index", label: "现场质控", icon: "star" },
  { path: "/index", label: "分析复核", icon: "excel" },
  { path: "/index", label: "分析审核", icon: "tree-table" },
  { path: "/index", label: "报告审查", icon: "build" },
  { path: "/index", label: "报告审核", icon: "eye" },
  { path: "/index", label: "报告发放", icon: "tab" },
  { path: "/index", label: "试剂管理", icon: "table" },
]);

const scheduleList = ref();
const topStatics = ref([
  {
    title: "报价",
    title1: "总计",
    title2: "转化",
    total1: 128,
    total2: 49,
    icon: "el-icon-suitcase",
    backgroundColor: "#398574",
  },
  {
    title: "合同",
    title1: "登记",
    title2: "审核",
    total1: 128,
    total2: 49,
    icon: "el-icon-suitcase",
    backgroundColor: "#398574",
  },
  {
    title: "采样",
    title1: "总计",
    title2: "完成",
    total1: 128,
    total2: 49,
    icon: "el-icon-suitcase",
    backgroundColor: "#398574",
  },
  {
    title: "样品库",
    title1: "总计",
    title2: "待领",
    total1: 128,
    total2: 49,
    icon: "el-icon-suitcase",
    backgroundColor: "#398574",
  },
  {
    title: "样品预警",
    title1: "待领",
    title2: "临期预警",
    total1: 128,
    total2: 49,
    icon: "el-icon-suitcase",
    backgroundColor: "#f56c6c",
  },
  {
    title: "分析",
    title1: "总计",
    title2: "完成",
    total1: 128,
    total2: 49,
    icon: "el-icon-suitcase",
    backgroundColor: "#398574",
  },
  {
    title: "报告预警",
    title1: "待发",
    title2: "临期预警",
    total1: 128,
    total2: 49,
    icon: "el-icon-suitcase",
    backgroundColor: "#f56c6c",
  },
  {
    title: "现场仪器",
    title1: "出库",
    title2: "入库",
    total1: 128,
    total2: 49,
    icon: "el-icon-suitcase",
    backgroundColor: "#398574",
  },
  {
    title: "仪器检定",
    title1: "总计",
    title2: "临期预警",
    total1: 128,
    total2: 49,
    icon: "el-icon-suitcase",
    backgroundColor: "#f56c6c",
  },
  // {title:'报价','total1':128,'total2':49,icon:'el-icon-suitcase',backgroundColor: "#398574"},
  // {title:'报价','total1':128,'total2':49,icon:'el-icon-suitcase',backgroundColor: "#398574"},
  // {title:'报价','total1':128,'total2':49,icon:'el-icon-suitcase',backgroundColor: "#398574"},
]);
function handleProcessList() {
  queryProgressList(queryProgressParams.value).then((res) => {
    scheduleList.value = res.rows;
    progressTotal.value = res.total;
  });
}
getCurrentTime().then((res) => {
  queryProgressParams.value.planDate = res.data.substring(0, 7);
  handleProcessList();
});

function handleTaskCount() {
  todoCount({}).then((res) => {
    if(res.data && res.data.length > 5){
      res.data.splice(5);//最多只保留5个
    }
    taskCountList.value = res.data;
  });
}
handleTaskCount();
const loading = ref(false);

function percentage(val) {
  if (!val.progressRate || val.progressRate == "") {
    return 0;
  }
  return parseInt(val.progressRate.replace("%", ""));
}

// 折柱混合图
const myChart0 = ref();
const myChart1 = ref();
function gain1() {
  var option = {
    title: {
      text: "月度工作量统计",
      left: "17%",
      textStyle: {
        fontSize: 14,
      },
    },
    tooltip: {
      trigger: "item",
      formatter: "{b} <br/>占比: {d}%", // 展示格式
    },
    legend: {
      orient: "vertical",
      right: "10%",
    },
    series: [
      {
        name: "月度工作量统计",
        type: "pie",
        radius: "50%",
        center: ["30%", "50%"],
        label: {
          position: "inner",
          fontSize: 11,
        },
        data: [
          { value: 27, name: "方案评审" },
          { value: 21, name: "现场原始记录复核" },
          { value: 12, name: "分析记录审核" },
          { value: 67, name: "报告签审" },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        label: {
          fontSize: 11,
          show: true,
          position: "inner", // 数值显示在内部
          formatter: "{d}%", // 格式化数值百分比输出
        },
      },
    ],
  };
  echarts.init(document.getElementById("rightChar")).setOption(option);
}
function gain() {
  const days = [];
  const taskCount = [];
  const taskAvg = [];
  for (let i = 1; i <= 31; i++) {
    days.push(i);
    taskCount.push(Math.floor(Math.random() * 100) + 1);
    taskAvg.push(Math.floor(Math.random() * 100) + 1);
  }

  var option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999",
        },
      },
    },
    grid: {
      top: 10, //距离容器上边界40像素
    },
    // toolbox: {
    //   feature: {
    //     dataView: { show: true, readOnly: false },
    //     magicType: { show: true, type: ["line", "bar"] },
    //     restore: { show: true },
    //     saveAsImage: { show: true },
    //   },
    // },
    legend: {
      data: ["个人", "部内平均"],
      orient: "vertical", // 垂直排列
      top: "middle",
      right: "0",
    },
    xAxis: [
      {
        type: "category",
        data: days,
        axisPointer: {
          type: "shadow",
        },
      },
    ],
    yAxis: [
      {
        type: "value",
        name: "",
        min: 0,
        max: 100,
        interval: 20,
        axisLabel: {
          formatter: "{value}",
        },
      },
    ],
    series: [
      {
        name: "个人",
        type: "bar",
        tooltip: {
          valueFormatter: function (value) {
            return value;
          },
        },
        barWidth: "30%",
        data: taskCount,
      },
      {
        name: "部内平均",
        type: "line",
        yAxisIndex: 0,
        tooltip: {
          valueFormatter: function (value) {
            return value;
          },
        },
        data: taskAvg,
      },
    ],
  };
  const leftChar = document.getElementById("leftChar");
  //此下的4行判断是否渲染过不管用（图表容器的高度改变后图表没有适应）
  let myChart = echarts.getInstanceByDom(leftChar);
  if (myChart == null) {
    myChart = echarts.init(leftChar);
  }
  markRaw(myChart).setOption(option);
}

watch(
  () => route,
  (newVal) => {
    if (newVal.path == "/flowable/task/record/index") {
      const { path, name, meta } = newVal;
      routeViewStore.setRouteView1({ path, name, meta });
    }
  }
);

function getList() {
  loading.value = true;
  todoList(queryParams.value).then((response) => {
    needDealList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

getList();

function handleProcess(row) {
  if (routeViewStore.routeView1) {
    proxy.$tab.closePage(routeViewStore.routeView1);
  }
  let pathStr;
  if (row.moduleCode == -1) {
    if (row.formKey) {
      if (row.formKey == "sampleQc") {
        sampleViewRef.value.open = true;
        sampleViewRef.value.dialogTitle = "添加样品";
        sampleViewRef.value.isQc = 0;
        nextTick(() => {
          sampleViewRef.value.getWithId(row.taskId);
        });
        return;
      } else {
        pathStr = row.formKey;
      }
    } else {
      pathStr = "/flowable/task/record/index";
    }
  } else if (row.moduleCode == 9) {
    if (row.executionId == 0 || row.executionId == 3) {
      writeRef.value.lMId = row.taskId;
      writeRef.value.myId = row.procInsId;
      writeRef.value.tabsView();
    } else {
      checkRef.value.handleCheck(row.procInsId);
    }
    return;
  } else {
    pathStr = row.formKey;
  }
  router.push({
    path: pathStr,
    query: {
      procInsId: row.procInsId,
      executionId: row.executionId,
      deployId: row.deployId,
      taskId: row.taskId,
      projectId: row.businessKey,
      finished: true,
      path: "/index",
    },
  });
}

bus.on("dbSave", (val) => {
  getList();
});

bus.on("handleIndex", (val) => {
  getList();
});

const chartOption0 = ref({
  series: [
    {
      type: "liquidFill",
      radius: "70%", // 水球图的半径
      center: ["50%", "50%"], // 水球图的中心位置
      data: [0.1, 0.2], // 水球图的数据，支持多个数据点
      backgroundStyle: {
        borderColor: "transparent", // 水球图外围边框颜色
        borderWidth: 0, // 水球图外围边框宽度
        color: "transparent",
      },
      outline: {
        show: true,
        borderDistance: 0,
        itemStyle: {
          borderColor: "#4688cda3",
          borderWidth: 3,
        },
      },
      label: {
        color: "#4c63e2", // 水球图中心文字颜色
        fontSize: 10, // 水球图中心文字字号
        position: ["50%", "50%"], // 水球图中心文字位置
      },
    },
  ],
});

const chartOption1 = ref({
  series: [
    {
      type: "liquidFill",
      radius: "70%", // 水球图的半径
      center: ["50%", "50%"], // 水球图的中心位置
      data: [0.2, 0.1], // 水球图的数据，支持多个数据点
      backgroundStyle: {
        borderColor: "transparent", // 水球图外围边框颜色
        borderWidth: 0, // 水球图外围边框宽度
        color: "transparent",
      },
      outline: {
        show: true,
        borderDistance: 0,
        itemStyle: {
          borderColor: "#4c63e2",
          borderWidth: 3,
        },
      },
      label: {
        color: "#4c63e2", // 水球图中心文字颜色
        fontSize: 10, // 水球图中心文字字号
        position: ["50%", "50%"], // 水球图中心文字位置
      },
    },
  ],
});

function handleAllTodo(category, taskDefKey) {
  if (routeViewStore.routeView1) {
    proxy.$tab.closePage(routeViewStore.routeView1);
  }
  let params = {
    path: "/task/todo",
  };
  if (taskDefKey) {
    params.query = { category: category, taskDefKey: taskDefKey };
  }
  router.push(params);
}
function renderDeptTjChart() {
  nextTick(() => {
    // myChart.value = markRaw(echarts.init(document.getElementById("leftChar")));
    gain();
    // myChart1.value = markRaw(
    //   echarts.init(document.getElementById("rightChar"))
    // );
    gain1();
  });
}
const autoHeight = ref();
function getTableHeight() {
  console.log("getTableHeight");
  var box = document.getElementById("deptTj");
  var boxDistanceFromTop = box.getBoundingClientRect().top;
  autoHeight.value = window.innerHeight - boxDistanceFromTop - 10;
  // if (autoHeight.value < 300) {
  //   autoHeight.value = 300; //暂时写死
  // }
  renderDeptTjChart();
}

onUpdated(() => {
  console.log("onUpdated");
});
onMounted(() => {
  console.log("onMounted");
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);

    for (let i = 0; i <= 8; i++) {
      if (i == 4 || i == 6 || i == 8) {
        //临期预警
        chartOption0.value.series[0].color = ["#f56c6c"];
      } else {
        chartOption0.value.series[0].color = ["#409eff"];
      }
      let data1 = Math.floor(Math.random() * 10) / 10 + 0.1;
      let data2 = Math.floor(Math.random() * 10) / 10 + 0.1;
      if(data2 > data1){
        let data3 = data1;
        data1 = data2;
        data2 = data3;
      }
      console.log("{},{}",data1,data2);
      chartOption0.value.series[0].data = [data1,data2]
      markRaw(echarts.init(document.getElementById("chart" + i))).setOption(
        chartOption0.value
      );
    }
  });
});
onBeforeUnmount(() => {
  console.log("onBeforeUnmount");
  window.removeEventListener("resize", getTableHeight);
});
</script>

<style scoped lang="scss">
.number {
  color: #fff;
  background-color: var(--theme-deep-color);
  border-right: 1px #fff solid;
  padding: 15px;
  padding-left: 10px;
  font-size: 14px;
  width: 30%;
  border-radius: 5px 0 0 5px;
  display: inline-block;
  vertical-align: middle;
  cursor: pointer;
  height: 50px;
  text-align: center;
}

.text {
  color: #fff;
  background-color: var(--theme-deep-color);
  padding: 15px;
  font-size: 14px;
  width: 70%;
  border-radius: 0 5px 5px 0;
  display: inline-block;
  vertical-align: middle;
  cursor: pointer;
  height: 50px;
  text-align: center;
}

.number_sub {
  color: #fff;
  width: 30%;
  background-color: var(--theme-deep-color);
  border-right: 1px #fff solid;
  padding: 5px;
  font-size: 12px;
  border-radius: 5px 0 0 5px;
  display: inline-block;
  vertical-align: middle;
  cursor: pointer;
  height: 24px;
  text-align: center;
}

.text_sub {
  color: #fff;
  width: 70%;
  background-color: var(--theme-deep-color);
  padding: 5px;
  font-size: 12px;
  border-radius: 0 5px 5px 0;
  display: inline-block;
  vertical-align: middle;
  cursor: pointer;
  height: 24px;
  text-align: center;
}

:deep(.el-tabs__nav) {
  margin-left: 120px;
}

.main_body {
  border: solid 2px #b6c2e2;
  border-radius: 10px;
}

// :deep(.el-scrollbar__view) {
//   height: 100%;
// }

.countColor {
  color: var(--theme-deep-color);
}
.taskAll {
  position: relative;
  height: 100%;
  width: 100%;
  .taski {
    display: flex;
    height: 100%;
    align-items: center;
    justify-content: center;
    line-height: 24px;
  }
  .item {
    // margin-right: 20px;
    background-color: rgba(66, 163, 255, 0.28);
    width: 30px;
    height: 30px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.s-cricle {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  text-align: center;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.color {
  color: rgb(29, 106, 221);
  font-size: 14px;
}
.innerbox::-webkit-scrollbar {
  width: 4px;
  height: 4px;
}
.innerbox::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(0, 0, 0, 0.2);
}
.innerbox::-webkit-scrollbar-track {
  -webkit-box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 0;
  background: rgba(0, 0, 0, 0.1);
}

ul,
li {
  list-style-type: none;
  margin: 0;
}
ul {
  list-style-type: none;
  margin: auto;
  padding: 0;
  > li {
    width: 200px;
  }
}

.top-ui {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
}

/* 自定义的小圆点样式 */
.title-dot {
  display: inline-block;
  width: 8px;
  /* 圆点直径 */
  height: 8px;
  /* 圆点直径 */
  border-radius: 50%;
  background-color: #398574;
  /* 圆点颜色 */
  margin-right: 5px;
  /* 圆点与文本间距 */
}

@import "@/assets/styles/mixin.scss";
.clearfix {
  @include clearfix;
  float: left;
  padding: 1px 5px;
  // margin-right: 10px;
  > div {
    float: left;
  }
}
</style>
